package com.powernode.listener;

import cn.hutool.core.collection.CollectionUtil;
import com.powernode.constant.AuthConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 关闭后台服务器时清除redis中的令牌TOKEN
 */
@Component
@Slf4j
public class ShutDownListener implements ApplicationListener<ContextClosedEvent> {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        log.info("Dlyk Application is Shutting Down ... ...");
        // 从redis中获取用户的所有令牌TOKEN
        Set<String> keys = stringRedisTemplate.keys(AuthConstants.TOKEN_REDIS_KEY_PREFIX + "*");
        if (CollectionUtil.isNotEmpty(keys)) {
            // 清除redis中的所有令牌TOKEN
            stringRedisTemplate.delete(keys);
        }

    }
}
